import socket
import uuid
import configparser 
import random
import os
import paramiko
import importlib

class Apis:

    def __init__(self):
        """
        Initializes an instance of the class.
        Reads the IP, port, username, and password from the configuration file.
        Establishes an SSH connection to the device using the provided credentials.
        """
        try:
            self._ip = self.read_item_from_config_ini('dev', 'ip')
            self._port = self.read_item_from_config_ini('dev', 'port')
            self._username = self.read_item_from_config_ini('dev', 'username')
            self._password = self.read_item_from_config_ini('dev', 'password')

            ssh_client =  paramiko.SSHClient()   
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            ssh_client.connect(
                hostname=self._ip,
                port=self._port,
                username=self._username,
                password=self._password
            )
            self._c = ssh_client

        except:
            print('INFO: Can not connect to device ...')
            self._c = None
  

    def connect_test(self):
        shell_command = "uname -a"
        stdin, stdout, stderr = self._c.exec_command(shell_command)
        stdout_info = stdout.read().decode('utf8')
        print(stdout_info)


    def connect_query(self, cmdstr):
            """
            Connects to a switch and executes a command.

            Args:
                cmdstr (str): The command to be executed.

            Returns:
                str: The output of the executed command.

            Raises:
                Exception: If unable to connect to the switch after multiple attempts.
            """
            count = 0
            while True:
                try:
                    shell_command = cmdstr
                    stdin, stdout, stderr = self._c.exec_command(shell_command)
                    stdout_info = stdout.read().decode('utf8')
                    return stdout_info
                except:
                    count += 1
                    if count > 3:
                        print('Error: Can not connect to switch ...')
                        return 'Error: Can not connect to switch ...'
                    else:
                        print('reload apis module ...')
                        importlib.reload(Apis)



    def read_item_from_config_ini(self, section, item):
        # print(os.system('pwd'))
        # print('==================================')
        cf = configparser.ConfigParser()
        cf.read('./Config.ini', encoding='gbk')
        return cf.get(section, item)


    def write_item_to_config_ini(self, section, item, value):
        cf = configparser.ConfigParser()
        cf.read('./Config.ini', encoding='gbk')
        cf.set(section, item, value)
        with open('./Config.ini', 'w') as configfile:
            cf.write(configfile)
        return 'save to Config.ini, ok.'

    def get_product(self):
        # product_val = self.din_get(12)
        # if int(product_val) == 0:
        #     return "OSFP"
        # else: # 1
        #     return "QSFP-DD"
        product_val = self.read_item_from_config_ini('dev', 'product')
        return product_val


    # INTERNAL_VERSION
    def is_for_customer(self):
        for_customer = self.read_item_from_config_ini('gui', 'for_customer')
        if for_customer == "INTERNAL_VERSION":
            return ''
        else:
            return 'hide'
        
    #####################################################################################################
    #
    # The following is the API for the Switch, which is not implemented yet.
    # Function: ...
    #
    #####################################################################################################
    